package com.team.weigou.utils;

import android.graphics.Bitmap;
import android.os.Build;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader;

public class AppImageCache implements ImageLoader.ImageCache {
    private static LruCache<String, Bitmap> lruCache;
    private static AppImageCache appImageCache;

    static {
        lruCache = new LruCache<String,Bitmap>(4 * 1024 * 1024){

            @Override
            protected int sizeOf(String key, Bitmap value) {
                return getBitmapSize(value);
            }
        };

    }

    private AppImageCache(){

    }

    public synchronized static AppImageCache getInstance(){
        if (appImageCache==null){
            appImageCache=new AppImageCache();
        }
        return appImageCache;
    }

    public static int getBitmapSize(Bitmap bitmap){
        int bitmapSize = 0;
        if (Build.VERSION.SDK_INT>Build.VERSION_CODES.HONEYCOMB_MR1){
            bitmapSize = bitmap.getByteCount();
        }else {
            bitmapSize = bitmap.getHeight()*bitmap.getRowBytes();
        }
        return bitmapSize;
    }

    /**
     * 获取图片
     *
     * @param url
     * @return
     */
    @Override
    public Bitmap getBitmap(String url) {
        return lruCache.get(url);
    }

    /**
     * 保存图片
     *
     * @param url
     * @param bitmap
     */
    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        lruCache.put(url,bitmap);
    }
}
